const Common = {
  //callback确定之后的回调
  myConfirm: function (content, options) {
    let promise = new Promise((resolve, reject) => {
      let defaultOptions = {
        title: "提示",
        content: content,
        confirmText: "确定",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            resolve();
          } else {
            reject();
          }
        }
      }
      options = extend(defaultOptions, options);
      wx.showModal(options);
    })
    return promise;
  },
  myAlert: function (content, options) {
    let promise = new Promise((resolve, reject) => {
      let defaultOptions = {
        content: content,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            resolve();
          }
        }
      }
      options = extend(defaultOptions, options);
      wx.showModal(options);
    });
    return promise;
  },
  //可以手动调用wx.hideToast()关闭Toast
  myToast: function (text, time) {
    wx.showToast({
      title: text ? text : '已完成',
      icon: 'success',
      duration: time ? time : 3000
    });
  },
  //可以手动调用wx.hideToast()关闭Toast
  loading: function (title, time) {
    wx.showToast({
      title: title ? title : '数据加载中',
      icon: 'loading',
      duration: time ? time : 3000,
    });
  }
}
// 将后台传过来的富文本字符串，转化为数组。
const transform = {
  params: function (param) { //拼接url的参数
    var _str = "?";
    for (let item in param) {
      if (param[item] != undefined) {
        _str += item + "=" + param[item] + "&";
      }
    }
    return _str.substring(0, _str.length - 1);
  },
  safeHtml: function (html) { //将富文本内容转化为字符串数组。
    var arr = [];
    arr = html.split("<br>");
    console.log(arr);
    return arr;
  },
  br2ln: function (strs) {//将br转成\n
    return strs.replace(/<br>/g, "\r\n");
  }
}
// 封装一个公共路由
const Router = {
  navigateTo: function (url, params) {
    let promise = new Promise((resolve, reject) => {
      let args = transform.params(params);
      wx.navigateTo({
        url: url + args,
        success: function (res) {
          resolve(res.data)
        },
        fail: function (errMsg) {
          reject(errMsg)
        }
      })
    })
    return promise;
  },
  redirectTo: function (url, params) {
    let promise = new Promise((resolve, reject) => {
      let args = transform.params(params);
      wx.redirectTo({
        url: url + args,
        success: function (res) {
          resolve(res.data)
        },
        fail: function (errMsg) {
          reject(errMsg)
        }
      });
    });
    return promise;
  },
  navigateBack: (num) => {
    wx.navigateBack({
      delta: num
    })
  }
}

module.exports = {
  Router: Router,
  transform: transform,
  Common: Common
}